package live.jipiao.dao;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import live.common.AirParam;
import live.common.DBHelper;
import live.common.ErrorException;
import live.common.Verifystring;
import live.jipiao.entity.AirOrder;
import live.jipiao.entity.AirQuery;
import live.jipiao.entity.FlightItem;
import live.jipiao.entity.PnrInfo;
import live.jipiao.entity.RateInfos;
import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;



public class CreateOrder {
	private FlightCommon fc = null;
	private List<RateInfos> rateInfos=null;
	private XmlFormart xfm = null;
	private Verifystring verify=null;
	private Document doc = null;
	private String postResult=null;
	private AirOrder order=null;
	private String rateType=null;
	private int count=0;
	public String getRateType() {
		return rateType;
	}
	public void setRateType(String rateType) {
		this.rateType = rateType;
	}
	/**
	 * 创建机票订单
	 * @param query
	 * @param chooseFlights
	 * @param pnr
	 * @param memberNum
	 * @return
	 * @throws ErrorException
	 */
	public AirOrder createB2bOrder(AirQuery query,List<FlightItem> chooseFlights,PnrInfo pnr,String memberNum) throws ErrorException{
		try {
			postResult = returnResponse(query,chooseFlights,pnr);
			if(postResult!=null){
				xfm=new XmlFormart();
				doc = xfm.xmlToDocument(postResult);
				if (xfm.returnSingleNode(doc, "//is_success").equals("T")) {
					order = returnOrderValue(doc);
					order.setPhoneNum(query.getLinkPhone());
					order.setFile4(query.getLinkName());
					order.setFile1(query.getVoyageType());
					order.setRateId(returnChooseRateids(chooseFlights));
					//单程封装
					FlightItem from = chooseFlights.get(0);
					order.setPassengers(pnr.getPassengerInfo());
					order.setAircom(from.getAircom());
					order.setFile2(from.getAircomName());
					order.setSdate(query.getFromDate());
					order.setDepTime(new Timestamp(from.getDepTime().getTime()));
					order.setArrTime(new Timestamp(from.getArrTime().getTime()));
					order.setCabinCode(from.getCabinInfo().getCode());
					order.setCost(Double.valueOf(from.getTax())+Double.valueOf(from.getYq()));
					order.setModel(from.getModel());
					order.setFare(pnr.getFare());
					order.setFlightNo(from.getFlightNo());
					order.setScity(from.getScityName());
					order.setEcity(from.getEcityName());
					if(query.getVoyageType()==2){
					//去程封装
					FlightItem back = chooseFlights.get(1);
					order.setBackAircom(back.getAircom());
					order.setFile3(back.getAircomName());
					order.setBackCabinCode(back.getCabinInfo().getCode());
					order.setBackArrTime(new Timestamp(back.getArrTime().getTime()));
					order.setBackDepTime(new Timestamp(back.getDepTime().getTime()));
					order.setBackCost(Double.valueOf(back.getTax())+Double.valueOf(back.getYq()));
					order.setBackFare(back.getCabinInfo().getFare());
					order.setBackflightNo(back.getFlightNo());
					order.setBackModel(back.getModel());
					}
					order.setAgentFee(returnAgentFee(chooseFlights,order));
					order.setMemberNum(memberNum);
					order.setBookDate(new Timestamp(new Date().getTime()));
					order.setOrderTotal(Double.parseDouble(order.getOrderTotal().toString())+Double.parseDouble(order.getAgentFee().toString()));
					if(addNewOrderInfo(order)==0){
						throw new ErrorException(new DocumentException("订单录入时出现异常"));
					}
				}else{
					throw new ErrorException(xfm.returnSingleNode(doc, "//error"));
				}
			}
		} catch (ErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ErrorException(new DocumentException("创建B2B订单出现异常"+e.getMessage()));
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			throw new ErrorException(new DocumentException("创建B2B订单XML转换Document出现异常"+e.getMessage()));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new ErrorException(new DocumentException("创建B2B订单SQLException出现异常"+e.getMessage()));
		}
		return order;
	}
	
	/**
	 * 添加新订单记录
	 * @param order
	 * @return
	 * @throws SQLException
	 */
	private int addNewOrderInfo(AirOrder order) throws SQLException{
		DBHelper dh = DBHelper.getInstance();
		 StringBuffer sqlBuffer = new StringBuffer("INSERT INTO Plane_Order (orderNo,passengers,pnrNo,scity,ecity,flightNo,model,deptime,arrtime,fare,")
		 .append("discount,cabinCode,aircom,cost,orderTotal,payTotal,sdate,bookDate,orderStatus,memberNum,phoneNum,tradingfee,rateId,agentFee,file1,file2,file3,file4,webOrder)");
		sqlBuffer
	       .append("VALUES('").append(order.getOrderNo()).append("','").append(order.getPassengers())
	       .append("','").append(order.getPnrNo()).append("','").append(order.getScity()).append("','")
	       .append(order.getEcity()).append("','").append(order.getFlightNo()).append("'")
	       .append(",'").append(order.getModel())
	       .append("','").append(order.getDepTime()).append("',")
	       .append(order.getArrTime()!=null?"'"+order.getArrTime()+"'":"NULL").append(",")
	       .append(order.getFare()).append(",")
	       .append(order.getDiscount()).append(",'")
	       .append(order.getCabinCode()).append("','")
	       .append(order.getAircom()).append("',")
	       .append(order.getCost()).append(",")
	       .append(order.getOrderTotal()).append(",").append(order.getPayTotao()).append(",")
	       .append(order.getSdate()!=null?"'"+order.getSdate()+"'":"NULL").append(",").append(order.getBookDate()!=null?"'"+order.getBookDate()+"'":"NULL").append(",")
	       .append(order.getOrderStatus()).append(",").append(order.getMemberNum()!=null?"'"+order.getMemberNum()+"'":"NULL").append(",")
	       .append(order.getPhoneNum()!=null?"'"+order.getPhoneNum()+"'":"NULL")
	       .append(",").append(order.getAgentFee()).append(",'").append(order.getRateId()).append("',")
	       .append(order.getAgentFee()).append(",")
	       .append(order.getFile1()).append(",").append(order.getFile2()!=null?"'"+order.getFile2()+"'":"NULL")
	       .append(",").append(order.getFile3()!=null?"'"+order.getFile3()+"'":"NULL")
	       .append(",").append(order.getFile4()!=null?"'"+order.getFile4()+"'":"NULL")
	       .append(",'on')");
		int count = dh.update(sqlBuffer.toString());
		dh.close();
		return count;
	}
	/**
	 * 封装Order信息
	 * @return
	 */
	private AirOrder returnOrderValue(Document doc){
		Iterator i = doc.selectNodes("//OrderInformation/OrderItem").iterator();
		Element e= null;
		 while (i.hasNext()) {
	          e = (Element)i.next();
	          order = new AirOrder();
	          order.setOrderNo(e.elementTextTrim("OrderNo"));
	          order.setCost(e.elementTextTrim("JJRY"));
	          double orderTotal = Double.parseDouble(e.elementTextTrim("ParValue").toString())+Double.parseDouble(order.getCost().toString());
	          orderTotal = orderTotal*Integer.parseInt(e.elementTextTrim("PassengerCount").toString());
	          order.setOrderTotal(Double.valueOf(orderTotal));
	          order.setPayTotao(((Element)e.selectNodes("//ProfitItems/ProfitItem").get(0)).elementText("Amount"));
	          order.setPnrNo(e.elementTextTrim("Pnr"));
	          order.setOrderStatus(e.elementTextTrim("OrderStatus"));
	          order.setScity(e.elementTextTrim("Scity"));
	          order.setEcity(e.elementTextTrim("Ecity"));
	          double discount = Double.parseDouble(((Element)e.selectNodes("//ProfitItems/ProfitItem").get(0)).elementText("Discount"));
	          order.setDiscount(Double.valueOf(discount));
	          order.setOrderStatus(e.elementTextTrim("OrderStatus"));
	        }
		return order;
	}
	
	
	/**
	 * B2B订单创建接口返回XML信息
	 * @param item
	 * @return
	 */
	private String returnResponse(AirQuery query,List<FlightItem> chooseFlights,PnrInfo pnr) throws ErrorException {
		xfm = new XmlFormart();
		Map<String, String> params = xfm
				.returnPublicPostData(AirParam.B2B_ORDER.toString());
		fc = new FlightCommon();
		verify = new Verifystring();
		String flightInfo = fc.returnFlightInfo(query, chooseFlights);
		String pnrInfo = fc.returnPnrInfo(pnr);
		rateInfos = returnChooseRates(chooseFlights);
		String orderInfo = fc.returnOrderInfo(rateInfos);
		params.put("flightInfo", flightInfo);
		params.put("passengerInfo", pnr.getPassengerInfo());
		params.put("pnrInfo", pnrInfo);
		params.put("orderInfo", orderInfo);
		params.put("pnr", pnr.getCode());
		params.put("rateType", getRateType());
		String sign = verify.returnAirMd5Hex(params);
		params.put("sign", sign);
		try {
			postResult = WebServicesSub.getInstance().returnResult(params);
			 if (count < 3) {
			        if (postResult.contains("请求服务失败【"+count+"】")) {
			          count += 1;
			          returnResponse(query,chooseFlights,pnr);
			        }
			        else if ((postResult.contains("政策返点已变动")) || (postResult.contains("没匹配到政策"))) {
			          count++;
			          List<FlightItem> newFlights = new ArrayList<FlightItem>();
			          for (FlightItem flightItem : chooseFlights) {
						flightItem.getCabinItem().getRateId();
						newFlights.add(flightItem);
			          }
			          returnResponse(query,newFlights,pnr);
			        }
			 }
			      count=0;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			postResult = null;
			throw new ErrorException("创建订单时出现异常"+e.getMessage());
		}finally{
			xfm=null;fc=null;verify=null;
		}
		return postResult;
	}
	/**
	 * 抽出选中航班匹配的政策信息
	 * @param chooseFlights
	 * @return
	 */
	private List<RateInfos> returnChooseRates(List<FlightItem> chooseFlights){
		rateInfos = new ArrayList<RateInfos>();
		RateInfos rateItem=null;
		int count=0;
		StringBuffer rateBuffer = new StringBuffer();
		for (FlightItem flightItem : chooseFlights) {
//			rateItem = flightItem.getCabinInfo().getRate();
//			rateBuffer.append(rateItem.getRateType().equals("7")?"1":rateItem.getRateType());
//			if(count!=chooseFlights.size()-1){
//				rateBuffer.append("|");
//			}
//			count++;
//			rateInfos.add(rateItem);
		}
		this.setRateType(rateBuffer.toString());
		return rateInfos;
	}
	private String returnChooseRateids(List<FlightItem> chooseFlights){
		RateInfos rateItem=null;
		int count=0;
		StringBuffer rateBuffer = new StringBuffer();
//		for (FlightItem flightItem : chooseFlights) {
//			rateItem = flightItem.getCabinInfo().getRate();
//			rateBuffer.append(rateItem.getRateNo());
//			if(count!=chooseFlights.size()-1){
//				rateBuffer.append("^");
//			}
//			count++;
//		}
		return rateBuffer.toString();
	}
	private double returnAgentFee(List<FlightItem> chooseFlights,AirOrder order){
		RateInfos rateItem=null;
		double agentFee=0;
		double countFee=0;
		for (FlightItem flightItem : chooseFlights) {
//			rateItem = flightItem.getCabinInfo().getRate();
//			if(rateItem.getPayConfig().equals("1")){
//				agentFee=Double.parseDouble(rateItem.getAgentFee().toString())*order.getPassengerList().size();
//			}
//			if(rateItem.getPayConfig().equals("2")){
//				double disfare = Double.parseDouble(returnNumMoney(Double.parseDouble(order.getFare().toString())*(1.0-Double.parseDouble(order.getDiscount().toString()))+Double.parseDouble(order.getCost().toString())+""));
//				agentFee=Double.parseDouble(returnHalf(Double.parseDouble(rateItem.getAgentFee().toString())*disfare*order.getPassengerList().size()));
//			}
//			if(count!=chooseFlights.size()-1){
			countFee+=agentFee;
//			}
//			count++;
		}
		return countFee;
	}
	
	private String returnNumMoney(String strNumber) {
		String result = null;
		result = new BigDecimal(strNumber).setScale(0, 0).toString();
		result = new DecimalFormat("0.0").format(Double.parseDouble(result));
		return result;
	}
	
	private String returnHalf(double strNum) {
		String result = null;
		result = new BigDecimal(strNum).setScale(2, 4).toString();
		return result;
	}
	
	public static void main(String[] args) {
	String str="<jinri><is_success>T</is_success><response><OrderInformation>  <OrderItem>    <OrderNo>B10630102549643753</OrderNo>    <OrderStatus>-3</OrderStatus>    <RefundType>0</RefundType>    <ProxyerPNo>ssdzsw                                            </ProxyerPNo>    <SalesmanPNo>ssdzsw                                            </SalesmanPNo>    <PassengerType>1</PassengerType>    <IsChangePnr>0</IsChangePnr>    <Pnr>Y00000</Pnr>    <BigPnr>Y00000</BigPnr>    <OrderTime>2011-06-30 10:23:37</OrderTime>    <ParValue>680.0000</ParValue>    <JJRY>160.0000</JJRY>    <RateType>1</RateType>    <RateRemark/>    <PassengerCount>1</PassengerCount>    <OutTicketType>1</OutTicketType>    <RateId>00001908907L</RateId>  </OrderItem><FlightItems>  <FlightItem>    <Sdate>2011-07-01 15:10:00</Sdate>    <Scity>PEK</Scity>    <Edate>2011-07-01 17:20:00</Edate>    <Ecity>SHA</Ecity>    <FlightNo>HU7601    </FlightNo>    <Cabin>Q</Cabin>    <IsReturnFlight>0</IsReturnFlight>    <Terminal/>  </FlightItem></FlightItems><PassengerItems>  <PassengerItem>    <PassengerName>%c5%cb%b1%f3%bd%a3</PassengerName>    <CardType>1</CardType>    <CardNO>330324198711212836</CardNO>  </PassengerItem></PassengerItems><ProfitItems>  <ProfitItem>    <UserName>ssdzsw                                            </UserName>    <UserType>1</UserType>    <Discount>3.3000</Discount>    <Amount>818.0000</Amount>  </ProfitItem></ProfitItems></OrderInformation></response></jinri>";
	Document doc;
	try {
		doc = DocumentHelper.parseText(str.trim());
	
	Iterator i = doc.selectNodes("//OrderInformation/OrderItem").iterator();
	AirOrder order=null;
	Element e= null;
	 while (i.hasNext()) {
          e = (Element)i.next();
          order = new AirOrder();
          order.setOrderNo(e.elementTextTrim("OrderNo"));
          order.setCost(e.elementTextTrim("JJRY"));
          double orderTotal = Double.parseDouble(e.elementTextTrim("ParValue").toString())+Double.parseDouble(order.getCost().toString());
          orderTotal = orderTotal*Integer.parseInt(e.elementTextTrim("PassengerCount").toString());
          order.setOrderTotal(Double.valueOf(orderTotal));
          order.setPayTotao(((Element)e.selectNodes("//ProfitItems/ProfitItem").get(0)).elementText("Amount"));
          order.setPnrNo(e.elementTextTrim("Pnr"));
          order.setOrderStatus(e.elementTextTrim("OrderStatus"));
          order.setScity(e.elementTextTrim("Scity"));
          order.setEcity(e.elementTextTrim("Ecity"));
          double discount = Double.parseDouble(((Element)e.selectNodes("//ProfitItems/ProfitItem").get(0)).elementText("Discount"));
          order.setDiscount(Double.valueOf(discount));
          order.setOrderStatus(e.elementTextTrim("OrderStatus"));
        }
	 System.out.println(JSONObject.fromObject(order));
	} catch (DocumentException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}}
}
